var ADMIN = (function (parent, $) {
    var ztreeExtend = parent.ztreeExtend = parent.ztreeExtend || {};
    var selectedMulti = true, $relatedTarget;

    function eventHandler() {
        $(document).on('click', '#tiny-menu-ul > li', function () {
            $('.tiny-menu').children('#tiny-menu-ul').removeClass('in');
            saveZtreeStorage();
        });


        $(document).off('click', '.tree-box-title .input-group-btn > .btn');
        $(document).on('click', '.tree-box-title .input-group-btn > .btn', keywordSearch);

        $(document).on('mouseleave', '.wrapper > .wrapper-left', tinyMenuMoveHidden);

        $(document).on('mouseleave', '#tree a.curSelectedNode', function(){
            $(this).find('.tiny-menu').children('#tiny-menu-ul').removeClass('in');
        });

        $('.tree-box-content .ztree').scroll(scrollHideTinyMenu);
    }

    function tinyMenuMoveHidden(e) {
        var treeTinyMenu = $(this).find('.tree-box .tree-box-content > #tree .tiny-menu');
        $(this).find('.tree-box .tree-box-content').append(treeTinyMenu.attr('style', ''));
    }

    function keywordSearch() {
        var $ztree = $('.tree-box-content > .ztree');
        if ($ztree.length === 0) {
            return;
        }

        var keyword = $(this).parents('.input-group').find('input').val();
        var treeId = $ztree.attr('id');
        var treeObj = $.fn.zTree.getZTreeObj(treeId);
        var options = treeObj.setting;
        if (options.async.otherParam) {
            options.async.otherParam.keyword = keyword;
        }
        $ztree.after($('.tiny-menu').hide());
        $.fn.zTree.destroy(treeId);
        $.fn.zTree.init($ztree, options);
    }

    function addHoverDom(treeId, treeNode) {
        debugger
        var zTreeObj  = $.fn.zTree.getZTreeObj(treeId);
        var $treeNode_a = $("#" + treeNode.tId + "_a");
        var $tinyMenu =  $('#' + treeId).parent().find('.tiny-menu');
        var treeNodeIconSkin = treeNode && treeNode.iconSkin;
        var tinyMenuLiShow = zTreeObj.setting.tinyMenuLiShow || [];

        var containerWidth = $('#' + treeId).parent().width();
        var nodeP =  $treeNode_a.position();
        var tinyMenuLeft = nodeP.left +  $treeNode_a.width() + 12;
        var tinyMenuTop= nodeP.top + 5;
        if (tinyMenuLeft > containerWidth) {
            tinyMenuLeft = containerWidth;
        }

        $tinyMenu.css({
            display: 'block',
            left: tinyMenuLeft + 'px',
            top: tinyMenuTop + 'px'
        });

        debugger
        //判断是否显示组织菜单的选项
        if (tinyMenuLiShow.length > 0 ) {
            var $tinyMenuLi = $tinyMenu.find('#tiny-menu-ul li');
            $tinyMenuLi.hide();
            $tinyMenuLi.each(function (index, item) {
                if ((tinyMenuLiShow[index]).indexOf(treeNodeIconSkin) === -1) {
                    return;
                }

                if (!$(item).is('.delete-node')) {
                    $(item).show();
                } else {
                    //获取此节点下的子节点，如果没有子节点，返回为[];
                    var nodes = zTreeObj.getNodesByFilter(filterMenu, false, treeNode);
                    if (nodes.length === 0 && !treeNode.isParent) {
                        $(item).show();
                    }
                }
            });
        }

        $treeNode_a.append($tinyMenu);
        if ($tinyMenu.length === 0 ||
            (zTreeObj.setting.disableModifyLevel &&
            zTreeObj.setting.disableModifyLevel.indexOf(treeNodeIconSkin) !== -1)) {
            $tinyMenu.find('.collapse').hide();
            $tinyMenu.hide();
        } else {
            $tinyMenu.show();
            $tinyMenu.find('.collapse').show();
        }
    }

    //返回获取到的某个父节点下的子节点的集合。
    function filterMenu(Node){
        return Node;
    }

    function removeHoverDom(treeId, treeNode) {
        $('#' + treeId).parent().find('.tiny-menu').children('#tiny-menu-ul').removeClass('in');
        $('#' + treeId).parent().find('.tiny-menu').children('#tiny-menu-ul').hide();
    }

    function filter(treeId, parentNode, childNodes) {
        if (!childNodes) return null;
        for (var i = 0, l = childNodes.length; i < l; i++) {
            childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
        }
        if(!parentNode === false){
            if (parentNode.checked === true) {
                for (var i = 0, l = childNodes.length; i < l; i++) {
                    childNodes[i].checked = parentNode.checked;
                }
            }
        }

        return childNodes;
    }

    function zTreeBeforeCheck(treeId, treeNode) {
        var zTreeObj  = $.fn.zTree.getZTreeObj(treeId);
        if (!treeNode ||
            treeNode.iconSkin &&
            zTreeObj.setting.allowLevelIcons &&
            zTreeObj.setting.allowLevelIcons.indexOf(treeNode.iconSkin) === -1) {
            return false;
        }
    }

    function zTreeOnCheck(e, treeId, treeNode){
        var treeObj = $.fn.zTree.getZTreeObj(treeId);
        treeObj.expandNode(treeNode, true, true);
    }

    /**
     * 当异步加载成功上，如果是首次加载树，
     * 如果缓存中已有选中节点，折恢复选中状态 （待完善）
     * @param e
     * @param treeId
     * @param treeNode
     */
    function zTreeOnAsyncSuccess(e, treeId, treeNode) {
        var _pNodesIdObj = $relatedTarget.parent().siblings('input[type="hidden"]').data('pNodesId');
        var storageNode = getZtreeStorage();
        if (!_pNodesIdObj && $('#' + treeId).parent().hasClass('.tree-box-content')) {
            _pNodesIdObj = storageNode;
        }
        expandParentNodes(treeId, _pNodesIdObj);

        if (storageNode) {
            var lastLevelNode = {};
            getLastLevelNode(storageNode, lastLevelNode);
            $('#' + treeId + ' #' + lastLevelNode.tId + '_a').trigger("click");
        }
    }

    /**
     * 获取父节点id
     * */
    function parentNodes(treeId, _selectedNodes) {
        var nodesData = {}, regroupSelectedNode;
        var treeObj = $.fn.zTree.getZTreeObj(treeId);
        if(typeof _selectedNodes === 'undefined' ||　_selectedNodes.length === 0){
            return null;
        }
        if (typeof _selectedNodes === 'string') {
            //=====单选时执行.
            var combinationArray = [];
            regroupSelectedNode = [];
            regroupPId(treeObj, _selectedNodes, regroupSelectedNode, combinationArray);
            _selectedNodes = regroupSelectedNode;
        } else {
            //=====多选时执行
            var isPId = treeObj.getNodeByParam("id", _selectedNodes[0], null);
            if (isPId.pId) {
                regroupSelectedNode = [];
                _selectedNodes.forEach(function (item) {
                    var combinationArray = [];
                    regroupPId(treeObj, item, regroupSelectedNode, combinationArray)
                });
                _selectedNodes = regroupSelectedNode;
            }
        }
        _selectedNodes.forEach(function (item) {
            combinationParentNodes(treeObj, treeId, item, nodesData);
        });
        return nodesData;
    }

    /**
     * 添加children对象的数据
     * */
    function setNodeChildren(pId, children, childrenNode) {
        children.some(function (item) {
            if (item.id === pId) {
                isNodeChildren(item.children, childrenNode);
                return;
            } else {
                setNodeChildren(pId, item.children, childrenNode);
            }
        })
    }

    /**
     * 重组父节点id
     * */
    function regroupPId(treeObj, selectedNodeId, regroupSelectedNode, combinationArray) {
        var combinationArray = combinationArray || [];
        var node = treeObj.getNodeByParam("id", selectedNodeId, null);
        if (regroupSelectedNode.indexOf(node.id) === -1) {
            combinationArray.push(node.id);
        }
        if(node.pId){
            regroupPId(treeObj, node.pId, regroupSelectedNode, combinationArray)
        } else {
            var isPId = treeObj.getNodeByParam("id", combinationArray[0], null);
            if (isPId.pId) {
                regroupSelectedNode.push.apply(regroupSelectedNode, combinationArray.reverse());
                return regroupSelectedNode;
            }else {
                regroupSelectedNode.push.apply(regroupSelectedNode, combinationArray);
                return regroupSelectedNode;
            }
        }
    }

    /**
     * 判断是否有相同id节点，有就不添加节点，没有就添加节点
     * */
    function isNodeChildren(childrenData, childrenNode){
        if (childrenData.length === 0) {
            childrenData.push(childrenNode);
        } else {
            var poprId = [];
            childrenData.forEach(function(item){
                poprId.push(item.id);
            });
            if(poprId.indexOf(childrenNode.id) === -1){
                childrenData.push(childrenNode);
            }
        }
    }

    /**
     * 把获取到的父节点id组合成一个对象数组.
     * */
    function combinationParentNodes(treeObj, treeId, item, nodesData) {
        var node = treeObj.getNodeByParam("id", item, null);
        var pNode = treeObj.getNodeByTId(node.parentTId);
        nodesData = nodesData || {};
        if (node.pId) {
            var childrenNode = {
                id: node.id,
                tId: node.tId,
                children: []
            };
            if (nodesData.id === node.pId) {
                isNodeChildren(nodesData.children, childrenNode);
            } else {
                setNodeChildren(node.pId, nodesData.children, childrenNode);
            }
            combinationParentNodes(treeObj, treeId, pNode.id, nodesData);
        } else {
            if (!nodesData.id) {
                nodesData.id = node.id;
                nodesData.tId = node.tId;
                nodesData.children = [];
            }
            return;
        }
    }

    /**
     * 回显时展开异步加载的节点
     * */
    function expandParentNodes(treeId, _pNodesIdObj) {
        if(!_pNodesIdObj){
            return;
        }
        var treeObj = $.fn.zTree.getZTreeObj(treeId);
        each_pNodesIdObj(treeObj, _pNodesIdObj);
    }

    function each_pNodesIdObj(treeObj, _pNodesIdObj){
        var node = treeObj.getNodeByParam("id", _pNodesIdObj.id, null);
        if(node !== null && node.open === false){
            treeObj.expandNode(node, true, false);
        }
        if (_pNodesIdObj.children.length !== 0) {
            _pNodesIdObj.children.forEach(function (item) {
                each_pNodesIdObj(treeObj, item);
            });
        }
    }

    /**
     * 拖拽到目标节点时，设置是否允许移动到目标节点前面的操作
     * @param treeId
     * @param nodes
     * @param targetNode
     * @returns {boolean}
     */
    function dropPrev(treeId, nodes, targetNode) {
        var pNode = targetNode.getParentNode();
        if (pNode && pNode.dropInner === false) {
            return false;
        } else {
            for (var i=0,l=curDragNodes.length; i<l; i++) {
                var curPNode = curDragNodes[i].getParentNode();
                if (curPNode && curPNode !== targetNode.getParentNode() && curPNode.childOuter === false) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 拖拽到目标节点时，设置是否允许成为目标节点的子节点
     * @param treeId
     * @param nodes
     * @param targetNode
     * @returns {boolean}
     */
    function dropInner(treeId, nodes, targetNode) {
        if (targetNode && targetNode.dropInner === false) {
            return false;
        } else {
            for (var i=0,l=curDragNodes.length; i<l; i++) {
                if (!targetNode && curDragNodes[i].dropRoot === false) {
                    return false;
                } else if (curDragNodes[i].parentTId && curDragNodes[i].getParentNode() !== targetNode && curDragNodes[i].getParentNode().childOuter === false) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 拖拽到目标节点时，设置是否允许移动到目标节点后面的操作
     * @param treeId
     * @param nodes
     * @param targetNode
     * @returns {boolean}
     */
    function dropNext(treeId, nodes, targetNode) {
        var pNode = targetNode.getParentNode();
        if (pNode && pNode.dropInner === false) {
            return false;
        } else {
            for (var i=0,l=curDragNodes.length; i<l; i++) {
                var curPNode = curDragNodes[i].getParentNode();
                if (curPNode && curPNode !== targetNode.getParentNode() && curPNode.childOuter === false) {
                    return false;
                }
            }
        }
        return true;
    }
    var curDragNodes;

    /**
     * 用于捕获节点被拖拽之前的事件回调函数，并且根据返回值确定是否允许开启拖拽操作
     * @param treeId
     * @param treeNodes
     * @returns {boolean}
     */
    function beforeDrag(treeId, treeNodes) {
        for (var i=0,l=treeNodes.length; i<l; i++) {
            if (treeNodes[i].drag === false) {
                curDragNodes = null;
                return false;
            } else if (treeNodes[i].parentTId && treeNodes[i].getParentNode().childDrag === false) {
                curDragNodes = null;
                return false;
            }
        }
        curDragNodes = treeNodes;
        return true;
    }


    /**
     *  初始化ZTree
     * @param options 设置ZTree参数
     * @param $target  目标树元素
     */
    function initZTree(options, $target) {
        var _options = {};
        _options.view = {
            fontCss : {
                color: "#666"
            },
            showLine: true,
            selectedMulti: true,
            dblClickExpand: true,
            addHoverDom: addHoverDom,
            removeHoverDom: removeHoverDom
        };
        _options.data = {
            simpleData: {
                //数据是否采用简单 Array 格式，默认false
                enable: true
            }
        };
        _options.async = {
            enable: true,
            url: options.url,
            autoParam: options.autoParam || ["id", "name=n", "level=lv"] ,
            otherParam: { keyword: "" },
            dataFilter: filter
        };

        _options.callback = {
            beforeCheck: zTreeBeforeCheck,
            onCheck: zTreeOnCheck,
            onAsyncSuccess: zTreeOnAsyncSuccess
        };

        $.extend(true, _options, options);

        selectedMulti = _options.selectedMulti;
        $relatedTarget = $(_options.relatedTarget);

        //修复页面左侧树形结构节点下拉菜单点击事件异常的问题
        if (_options.callback && _options.callback.onClick) {
            _options.callback.onClick = function(e, treeId, treeNode) {
                if ($(e.target).parents('.tiny-menu').length > 0) {
                    return false;
                }

                options.callback.onClick(e, treeId, treeNode);
                saveZtreeStorage();
            }
        }

        var scripts = [
            path +'/static/js/plugins/ztree/jquery.ztree.core.min.js',
            path +'/static/js/plugins/ztree/jquery.ztree.exedit.min.js',
            path +'/static/js/plugins/ztree/jquery.ztree.excheck.min.js'
        ];

        var $ztree = $target || $('.tree-box-content .ztree');
        parent.common.eachSeries(scripts, parent.common.getScript, function () {
            $.fn.zTree.init($ztree, _options);
        });
    }


    /**
     * 初始化可拖拽的ZTree
     * @param options 设置ZTree参数
     * @param $target 目标树元素
     * @param nodes  生成树的节点数据（可选）
     */
    function initDraggableZTree(options, $target, nodes) {
        var _options = {};
        _options.view = {
            fontCss : {
                color: "#666"
            },
            showLine: true,
            selectedMulti: false,
            dblClickExpand: false
        };

        if (options.selectedMulti) {
            _options.check = {
                enable: true,
                chkStyle: "checkbox"
            };
        }
        _options.edit = {
            drag: {
                autoExpandTrigger: true,
                prev: dropPrev,
                inner: dropInner,
                next: dropNext
            },
            enable: true,
            showRemoveBtn: false,
            showRenameBtn: false
        };
        _options.data = {
            simpleData: {
                //数据是否采用简单 Array 格式，默认false
                enable: true
            }
        };
        _options.async = {
            enable: true,
            url: options.url,
            autoParam: options.autoParam || ["id", "name=n", "level=lv"] ,
            otherParam: { keyword: "" },
            dataFilter: filter
        };

        //如果已有节点数据，禁用异步加载模式
        if (nodes && nodes.length > 0) {
            _options.async.enable = false;
        }

        _options.callback = {
            beforeDrag: beforeDrag
        };

        $.extend(true, _options, options);

        var scripts = [
            path +'static/js/plugins/zTree/jquery.ztree.core.min.js',
            path +'static/js/plugins/zTree/jquery.ztree.exedit.min.js',
            path +'static/js/plugins/zTree/jquery.ztree.excheck.min.js'
        ];

        var $ztree = $target || $('.draggable-ztree');
        parent.common.eachSeries(scripts, parent.common.getScript, function () {
            $.fn.zTree.init($ztree, _options, nodes);
        });
    }

    /**
     * 获取父节点id的数组
     * @param treeObj
     * @param ztreeId
     * @returns {{}}
     */
    function getSelectedNode(treeObj, ztreeId) {
        var selectedNodesArr = [];
        $('#'+ztreeId +' li[treenode]').each(function (index, item) {
            var $selectedNode = $(item).find('.curSelectedNode');
            if ($selectedNode.length > 0) {
                var node = treeObj.getNodeByTId($(item).attr('id'));
                selectedNodesArr.push(node);
            }
        });

        var selectedNodes = {};
        selectedNodesArr.forEach(function (node) {
            combinationParentNodes(treeObj, ztreeId, node.id, selectedNodes);
        });

        return selectedNodes;
    }

    /**
     * 获取选中的根节点tId
     * @param storageNode
     * @returns {*}
     */
    function getLastLevelNode(storageNode, lastLevelNode) {
        lastLevelNode = lastLevelNode || {};
        if (storageNode.children.length > 0) {
            getLastLevelNode(storageNode.children[0], lastLevelNode);
            return;
        }

        lastLevelNode.tId = storageNode.tId;
    }

    /**
     * 保存当前页面的左侧树形结构状态
     */
    function saveZtreeStorage() {
        var $leftZtree = $('.tree-box-content .ztree');
        if ($leftZtree.length === 0) {
            return;
        }
        var ztreeId = $leftZtree.attr('id');
        if (ztreeId === '') {
            return;
        }
        var treeObj = $.fn.zTree.getZTreeObj(ztreeId);
        var nodes = treeObj.getSelectedNodes();
        if (nodes.length > 0) {
            var parentNode = getSelectedNode(treeObj, ztreeId);
            localStorage.setItem("activeZtree", JSON.stringify(parentNode));
        }
    }

    // 获取本地存储中的左侧树形结构状态
    function getZtreeStorage() {
        return JSON.parse(localStorage.getItem("activeZtree"))|| null;
    }

    // 清除本地存储中的左侧树形结构状态
    function clearZtreeStorage() {
        localStorage.removeItem("activeZtree");
    }

    function scrollHideTinyMenu() {
        $('.ztree .tiny-menu').hide();
    }

    ztreeExtend.initZTree = initZTree;
    ztreeExtend.initDraggableZTree = initDraggableZTree;
    ztreeExtend.saveZtreeStorage = saveZtreeStorage;
    ztreeExtend.getZtreeStorage = getZtreeStorage;
    ztreeExtend.clearZtreeStorage = clearZtreeStorage;
    ztreeExtend.parentNodes = parentNodes;
    ztreeExtend.init = function () {
        eventHandler();
    };

    return parent;
}(ADMIN || {}, jQuery));